package cfg

import (
	"encoding/json"
	"gofar/app/model"
	"gofar/packed/gerr"
	"os"

	"github.com/spf13/viper"
)

var (
	config model.Config
	path   = "./config"
)

func init() {
	viper.SetConfigName("config")
	viper.SetConfigType("json")
	viper.AddConfigPath(path)
}

func Read() {
	err := viper.ReadInConfig()
	if err != nil {
		panic(err)
	}
	if err = unmarshal(); err != nil {
		panic(err)
	}
}

func Set[T any](key string, value T) {
	viper.SetDefault(key, value)
	unmarshal()
}

func Get() *model.Config {
	return &config
}

func unmarshal() error {
	return viper.Unmarshal(&config)
}

// 保存
func Marshal() *gerr.Error {
	conf, err := json.Marshal(&config)
	if err != nil {
		return gerr.Swrap(&err, "Marshal config Err："+err.Error())
	}
	file, err := os.Create(path + "/config.json")
	if err != nil {
		return gerr.Swrap(&err, "配置文件路径错误："+err.Error())
	}
	defer file.Close()
	_, err = file.Write(conf)
	if err != nil {
		return gerr.Swrap(&err, "写入配置错误："+err.Error())
	}
	return nil
}
